package io.github.definitlyevil.ziminmod.listeners;

import io.github.definitlyevil.customitemframework.CIFItemInstance;
import io.github.definitlyevil.customitemframework.CustomItemFramework;
import io.github.definitlyevil.ziminmod.cif.armors.ZiMinChestplate;
import org.bukkit.Location;
import org.bukkit.entity.LivingEntity;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.inventory.ItemStack;

import java.util.Random;

public class ZiMinChestplateListener implements Listener {

    private final Random random = new Random();

    @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
    public void onDamage(EntityDamageEvent event) {
        if(!LivingEntity.class.isAssignableFrom(event.getEntity().getClass())) return;
        // 获取受伤的实体
        LivingEntity living = (LivingEntity) event.getEntity();
        if(!checkZiMinChestplate(living)) return;
        // 如果嗝儿屁了的话就不要再播放受伤音效了！
        if(living.getHealth() - event.getFinalDamage() <= 0) return;
        // 现在是检测到了是针男人胸甲，所以播放声♂音
        Location location = event.getEntity().getLocation();
        // 随机 +或- 0.2的音高
        location.getWorld().playSound(
            location,
            "zimin.ah.random",
            1.0f,
            1.0f + ((random.nextBoolean() ? 1f : -1f) * random.nextFloat() * 0.2f)
        );
    }

    @EventHandler(priority = EventPriority.MONITOR)
    public void onDeath(EntityDeathEvent event) {
        LivingEntity living = event.getEntity();
        if(!checkZiMinChestplate(living)) return;
        // 现在是检测到了是针男人胸甲，所以播放声♂音
        Location location = event.getEntity().getLocation();
        // 随机 +或- 0.2的音高
        location.getWorld().playSound(
            location,
            "zimin.death",
            1.0f,
            1.0f + ((random.nextBoolean() ? 1f : -1f) * random.nextFloat() * 0.2f)
        );
    }

    private static boolean checkZiMinChestplate(LivingEntity living) {
        // 检查一下是不是支持装备而且有胸甲
        if(living.getEquipment() == null || living.getEquipment().getChestplate() == null) return false;
        ItemStack chestplate = living.getEquipment().getChestplate();
        CIFItemInstance instance = CustomItemFramework.getCIFDataFromItem(chestplate);
        // 如果不是针男人胸甲，就白白
        if(instance == null || !ZiMinChestplate.class.isAssignableFrom(instance.type.getClass())) return false;
        return true;
    }

}
